/*
 * @lc app=leetcode.cn id=120 lang=golang
 *
 * [120] 三角形最小路径和
 */

// 3. 动态规划，再2的基础上优化了代码
// @lc code=start
func minimumTotal(triangle [][]int) int {
	level := len(triangle)

	dp := make([][]int, level)
	for i := 0; i < len(triangle); i++ {
		dp[i] = make([]int, len(triangle[i]))
	}

	dp[0][0] = triangle[0][0]
	for i := 1; i < len(triangle); i++ {
		for j := 0; j < len(triangle[i]); j++ {
			if j == 0 {
				dp[i][j] = dp[i-1][j] + triangle[i][j]
			} else if j == len(triangle[i])-1 {
				dp[i][j] = dp[i-1][j-1] + triangle[i][j]
			} else {
				dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]
			}

		}
	}

	ans := math.MaxInt64
	for i := 0; i < len(dp[level-1]); i++ {
		ans = min(ans, dp[level-1][i])
	}
	return ans
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

// @lc code=end

// 2. 动态规划
// @lc code=start
func minimumTotal(triangle [][]int) int {
	level := len(triangle)

	dp := make([][]int, level)
	for i := 0; i < len(triangle); i++ {
		dp[i] = make([]int, len(triangle[i]))
		if i == 0 {
			dp[i][0] = triangle[i][0]
			continue
		}

		dp[i][0] = dp[i-1][0] + triangle[i][0]
		dp[i][len(triangle[i])-1] = dp[i-1][len(triangle[i])-2] + triangle[i][len(triangle[i])-1]
	}

	for i := 1; i < len(triangle); i++ {
		for j := 1; j < len(triangle[i])-1; j++ {
			dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]
		}
	}

	ans := math.MaxInt64
	for i := 0; i < len(dp[level-1]); i++ {
		ans = min(ans, dp[level-1][i])
	}

	return ans
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

// @lc code=end

// 1. 深度优先 超时 42/44
// @lc code=start
func minimumTotal(triangle [][]int) int {
	ans := math.MaxInt64
	var dfs func(level, index, sum int)
	dfs = func(level, index, sum int) {
		if level == len(triangle)-1 {
			ans = min(ans, sum+triangle[level][index])
			return
		}

		dfs(level+1, index, sum+triangle[level][index])
		dfs(level+1, index+1, sum+triangle[level][index])
	}

	dfs(0, 0, 0)
	return ans
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

// @lc code=end

